<template>
<div>
    <div class="config">
        <div class="item" v-for="(tempI,index) in maxLength" :key="index">
            <div class="header center between">
                <div class="input-wrap">
                    <label>{{config.keyArr[index].key_param[0]}}号键</label>
                    <el-input size="mini" v-model="config.keyArr[index].key_name" style="width:140px;" placeholder="按键名称" class="bold-input"></el-input>
                </div>
                <div class="input-wrap">
                    <div class="input-wrap">
                        <label>上电</label>
                        <el-select size="mini" class="input-item" v-model="config.keyArr[index].key_param[1]">
                            <el-option v-for="i in rememberDict" :key="i.label" :label="i.label" :value="i.value"></el-option>
                        </el-select>
                    </div>
                </div>
            </div>
            
            <div class="mid center between">
                <div class="input-wrap">
                    <label>长按时长</label>
                    <el-input size="mini" class="input-item" style="width:50px" v-model.number="config.keyArr[index].key_param[2]" @input="limit1To60(config.keyArr[index].key_param[2],index)"></el-input>
                    <span style="margin-left:10px;">秒</span>
                </div>
                <div class="input-wrap">
                    <label>关联设备</label>
                    <el-input size="mini" class="input-item" v-model.number="config.keyArr[index].key_param[3]"></el-input>
                </div>
            </div>

            <div class="bot center between">
                <div class="input-wrap" style="width:100%;">
                    <label>关联键号</label>
                    <el-select
                        style="flex:1;"
                        size="mini"
                        v-model="config.keyArr[index].key_code_arr"
                        multiple
                        filterable
                        allow-create
                        default-first-option
                        placeholder="请选择关联设备的键号">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </div>
            </div>

            <div class="mid">
                <div>事件列表</div>
                <div v-if="config.keyArr[index].key_led_events.length===0&&config.keyArr[index].key_relay_events.length===0" class="center row-center" style="padding:10px 0;">暂无事件</div>
                <template v-else>
                    <task-list :taskList="config.keyArr[index].key_led_events" @editConfig="editConfig" :index="index" @delConfig="delConfig"></task-list>
                    <task-list :taskList="config.keyArr[index].key_relay_events" @editConfig="editConfig" :index="index" @delConfig="delConfig"></task-list>
                </template>
            </div>
            <div class="footer" @click="openTaskDialog(index)">添加事件</div>
        </div>
    </div>
    <el-dialog
        title="事件添加"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" size="mini">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="触发事件">
                        <el-select class="input-item" v-model="ruleForm.emitEvent">
                            <el-option v-for="i in emitEventDict" :key="i.label" :label="i.label" :value="i.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="触发">
                        <el-select class="input-item" v-model="ruleForm.values[0]">
                            <el-option v-for="i in emitTypeDict" :key="i.label" :label="i.label" :value="i.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="执行">
                        <el-select class="input-item" v-model="ruleForm.values[1]">
                            <el-option v-for="i in switchDict" :key="i.label" :label="i.label" :value="i.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <template v-if="[4,5,6].includes(ruleForm.values[1])">
                    <el-col :span="8">
                        <el-form-item label="延时">
                            <el-input v-model.number="ruleForm.values[3]"></el-input>
                        </el-form-item>
                    </el-col>
                    <span style="line-height:28px;margin-left:20px;">x100毫秒</span>
                </template>
            </el-row>
            <el-form-item label="触发对象">
                <div class="expand flex" :style="{width:ruleForm.emitEvent===1?'50%':''}">
                    <template v-if="ruleForm.emitEvent===0">
                        <light-check-box v-for="(i,ind) in 8" v-model="ruleForm.checkList[ind]" :key="i" :index="ind" :disabled="false&&disableCheckList[chooseIndex].includes(ind+1)"></light-check-box>
                    </template>

                    <template v-else>
                        <jidian-check-box v-for="(i,ind) in 4" v-model="ruleForm.checkList[ind]" :key="i" :index="ind" :disabled="false&&disableCheckList[chooseIndex].includes(ind+1)"></jidian-check-box>
                    </template>
                </div>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogVisible = false">取消</el-button>
            <el-button size="mini" type="primary" @click="confirmEditEvent">确定</el-button>
        </span>
    </el-dialog>
</div>
</template>

<script>
import LightCheckBox from './LightCheckBox.vue'
import JidianCheckBox from './JidianCheckBox.vue'
import TaskList from './TaskList.vue'
export default {
  components:{
    LightCheckBox,TaskList,JidianCheckBox
  },
  props:{
    config:{
      type:Object,
      required:true
    }
  },
  data(){
      return {
        active:false,
        delay:10,
        chooseIndex:0,
        switchDict:[
            {value: 1,label: '反转'},
            {value: 2,label: '关'},
            {value: 3,label: '开'},
            {value: 4,label: '延时反转'},
            {value: 5,label: '延时关'},
            {value: 6,label: '延时开'},
            {value: 7,label: '点动'},
        ],
        switchModel:1,
        rememberDict:[
            {value: 0,label: '关'},
            {value: 1,label: '开'},
            {value: 2,label: '记忆'},
        ],
        rememberModel:0,
        codeArr:[1,2,3,4,5,6,7,8],
        mode:1,
        relateCode:1,
        lightArr:[],
        ledArr:[0,0,0,0,0,0,0,0],
        relayArr:[],
        checked: true,
        options: [
            {value: '1',label: '1'},
            {value: '2',label: '2'},
            {value: '3',label: '3'},
            {value: '4',label: '4'},
            {value: '5',label: '5'},
            {value: '6',label: '6'},
            {value: '7',label: '7'},
            {value: '8',label: '8'}
        ],
        value: [],
        // taskList:[
        //     { emitEvent:0,emitType:0,sleepTime:0.2,emitObject:['0','0','0','1','0','0','0','1'] },
        //     { emitEvent:1,emitType:0,sleepTime:0.2,emitObject:['0','0','0','1'] },
        // ],
        dialogVisible:false,
        ruleForm: {
            emitEvent:1,
            values:[1,2,3,4,5],
            labels:[0,1,2],
            checkList:['1','0','1','0','1','0','1','0']
        },
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ]
        },

        emitEventDict:[
            {value: 0,label: 'LED控制'},
            {value: 1,label: '继电器控制'},
        ],
        emitEventModel:0,

        emitTypeDict:[
            {value: 0,label: '按键短按'},
            {value: 1,label: '按键长按'},
        ],
        emitTypeModel:1,
        eventIndex:0,
        editFlag:false
      }
  },
//   watch:{
//       config:{
//           handler(val){
//               this.lightArr = val.lightArr.map(item=>{
//                   let temp = item.toString(2);
//                   return this.preZero(temp).split("").reverse();
//               })
//               this.ledArr = val.ledArr.map(item=>{
//                   let temp = item.toString(2);
//                   return this.preZero(temp).split("").reverse();
//               })
//               this.relayArr = val.relayArr.map(item=>{
//                   let temp = item.toString(2);
//                   return this.preZero4Bit(temp).split("").reverse();
//               })
//           },
//           deep:true,
//           immediate:true
//       }
//   },
  computed:{
      disableCheckList(){
          const tempArr = [];
          this.config.keyArr.forEach(item=>{
              let labelsArr = [];
              item.key_led_events.forEach(item2=>{
                  labelsArr = [...labelsArr,...item2.labels];
              })
              tempArr.push(labelsArr);
          })
          return tempArr;
      },
      maxLength(){
          let arr = [];
          this.config.keyArr.forEach(item=>{
              arr.push(item.key_param[0]);
          })
          return Math.max.apply(null, arr);
      }
  },
  methods:{
      limit1To60(val,index){
          if(val<1){
              this.config.keyArr[index].key_param[2] = 1;
              this.$message({
                  type:'error',
                  message:'范围1-60',
                  showClose:true
              })
          } else if(val>60){
              this.config.keyArr[index].key_param[2] = 60;
              this.$message({
                  type:'error',
                  message:'范围1-60',
                  showClose:true
              })
          }
      },
      confirmEditEvent(){
          const tempConfig = JSON.parse(JSON.stringify(this.config));
          if([4,5,6].includes(this.ruleForm.values[1])){
              if(this.ruleForm.values[3]>60){
                  this.$message({
                    showClose: true,
                    message: '应该小于60',
                    type: 'error'
                  })
                  return;
              } else if(this.ruleForm.values[3]<1){
                  this.$message({
                    showClose: true,
                    message: '应该大于1',
                    type: 'error'
                  })
                  return;
              }
          }
          const {chooseIndex,eventIndex} = this;
          if(!this.editFlag){
              this.ruleForm.labels = this.checkList2Labels(this.ruleForm.checkList);
              if(this.ruleForm.labels.length === 0){
                  this.$message({
                    showClose: true,
                    message: '请选择触发对象',
                    type: 'error'
                  })
                  return;
              }
            if(this.ruleForm.emitEvent === 0){
                tempConfig.keyArr[chooseIndex].key_led_events.push(this.ruleForm);
            } else {
                tempConfig.keyArr[chooseIndex].key_relay_events.push(this.ruleForm);
            }
          }else {
              if(this.checkList2Labels(this.ruleForm.checkList).length === 0){
                  this.$message({
                    showClose: true,
                    message: '请选择触发对象',
                    type: 'error'
                  })
                  return;
              }
              console.log(JSON.stringify(this.ruleForm));
            if(this.ruleForm.emitEvent === 0){
                tempConfig.keyArr[chooseIndex].key_led_events[eventIndex].labels = this.checkList2Labels(this.ruleForm.checkList);
                tempConfig.keyArr[chooseIndex].key_led_events[eventIndex].checkList = this.ruleForm.checkList;
                tempConfig.keyArr[chooseIndex].key_led_events[eventIndex].values = this.ruleForm.values;
            } else {
                tempConfig.keyArr[chooseIndex].key_relay_events[eventIndex].labels = this.checkList2Labels(this.ruleForm.checkList);
                tempConfig.keyArr[chooseIndex].key_relay_events[eventIndex].checkList = this.ruleForm.checkList;
                tempConfig.keyArr[chooseIndex].key_relay_events[eventIndex].values = this.ruleForm.values;
            }
          }
          this.$emit('confirmConfig',tempConfig);
          this.dialogVisible = false;
      },
      checkList2Labels(checkList){
        const labelList = [];
        for(let i=0;i<8;i++){
            if(checkList[i] === '1'){
                labelList.push(i+1);
            }
        }
        return labelList;
      },
      handleClose(){
        this.dialogVisible = false;
      },
      editConfig({item,index,eventIndex}){
        this.editFlag = true;
        this.ruleForm = JSON.parse(JSON.stringify(item));
        this.dialogVisible = true;
        this.chooseIndex = index;
        this.eventIndex = eventIndex;
        this.$forceUpdate();
      },
      delConfig({item,index,eventIndex}){
          this.$emit('delConfig',{item,index,eventIndex})
      },
      openTaskDialog(chooseIndex){
        this.chooseIndex = chooseIndex;
        this.editFlag = false;
        this.ruleForm = {
            emitEvent:1,
            values:[0,1,0,5,0],
            labels:[],
            checkList:['0','0','0','0','0','0','0','0']
        }
        this.dialogVisible = true;
      },
      preZero(val){
        let arr = []
        for(let i=0;i<8-val.length;i++){
            arr.push(0);
        }
        return arr.join("")+val
      },
      preZero4Bit(val){
        let arr = []
        for(let i=0;i<4-val.length;i++){
            arr.push(0);
        }
        return arr.join("")+val
      },
    //   toggleLight(){
    //     this.flatArr();
    //   },
    //   flatArr(){
    //       this.config.lightArr = this.lightArr.map(item=>parseInt(item.reverse().join(""),2));
    //       this.config.ledArr = this.ledArr.map(item=>parseInt(item.reverse().join(""),2));
    //       this.config.relayArr = this.relayArr.map(item=>parseInt(item.reverse().join(""),2));
    //   },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .bold-input .el-input__inner{
    color:#000000;
}
.config{
    display: grid;
    grid-template-columns: repeat(3,1fr);
    grid-row-gap: 1rem;
    grid-column-gap: 1rem;
    .item{
        border-radius: 10px;
        overflow: hidden;
        .header{
            background:#856FFA;
            padding:.5rem;
            color:white;
        }
        .mid{
            padding:0 .5rem;
            margin-top:.5rem;
        }
        .input-wrap{
            display: flex;
            align-items: center;
            label{
                margin-right:.5rem;
            }
            .input-item{
                max-width:100px;
            }
        }
        .bot{
            padding:.5rem;
            padding-top:.2rem;
            margin-top:.5rem;
        }
        .footer{
            color:white;
            background: #FF875F;
            text-align: center;
            padding:.5rem 0;
            cursor: pointer;
        }
    }
}
.two{
    display: flex;
    margin-top:1rem;
    border-right:1px solid rgba(0, 0, 0, .04);
    border-top:1px solid rgba(0, 0, 0, .04);
    .column{
        flex:1;
    }
    .header{
        span{
            background:#F1F4FF;
        }
    }
    span{
        padding:.5rem 0;
        flex:1;
        text-align: center;
        border-left:1px solid rgba(0, 0, 0, .04);
        border-bottom:1px solid rgba(0, 0, 0, .04);
        &:first-child{
          background:#F1F4FF;
        }
        .check{
          transform: scale(1.2);
        }
    }
}
</style>